// src/logical/auth/auth.service.ts
import { Injectable } from '@nestjs/common';
import { UserService } from '../user/user.service';
import { JwtService } from '@nestjs/jwt';
import { encryptPassword } from '../../utils/cryptogram';
import { ResultData } from 'src/utils/result';
import { AppHttpCode } from 'src/utils/code.enum';

@Injectable()
export class AuthService {
  constructor(private readonly usersService: UserService, private readonly jwtService: JwtService) {}

  // JWT验证 - Step 2: 校验用户信息
  async validateUser(username: string, password: string): Promise<ResultData> {
    console.log('JWT验证 - Step 2: 校验用户信息');
    const user = await this.usersService.findOne(username);
    if (user) {
      const hashedPassword = user.password;
      const salt = user.salt;
      // 通过密码盐，加密传参，再与数据库里的比较，判断是否相等
      const hashPassword = encryptPassword(password, salt);
      if (hashedPassword === hashPassword) {
        // 密码正确
        
        const payload = { username: user.username, sub: user.userId, realName: user.realName, role: user.role };
        console.log('JWT验证 - Step 3: 处理 jwt 签证');
        try {
          const token = this.jwtService.sign(payload);
          return ResultData.ok(token,"登录成功")
         
        } catch (error) {
          return ResultData.fail(AppHttpCode.FAIL,"帐号或密码错误")
          
        }
      } else {
        // 密码错误
        return ResultData.fail(AppHttpCode.FAIL,"帐号或密码错误")
      }
    }
    // 查无此人
    return ResultData.fail(AppHttpCode.FAIL,"查无此人")
  }

 
}
